package com.zhudoo.zhilian.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhudoo.zhilian.dao.entity.*;
import com.zhudoo.zhilian.dao.impl.ChatDao;
import com.zhudoo.zhilian.dao.impl.TipDao;
import com.zhudoo.zhilian.dao.impl.UserDao;
import com.zhudoo.zhilian.util.DateUtil;
import com.zhudoo.zhilian.util.MiniProgramUtil;
import com.zhudoo.zhilian.util.service.ChatUtil;
import com.zhudoo.zhilian.util.socket.SendSocketMessage;
import com.zhudoo.zhilian.util.web.BusinessException;
import com.zhudoo.zhilian.util.web.ServiceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author zhudao
 */
@Service
public class ChatService {

    /**
     * 文本
     */
    public static int text = 1;

    /**
     * 图片
     */
    public static int img = 2;

    /**
     * 地图
     */
    public static int map = 3;

    /**
     * 约看
     */
    public static int appointment = 4;

    /**
     * 时间
     */
    public static int date = 5;


    @Autowired
    UserDao userDao;
    @Autowired
    ChatDao chatDao;
    @Autowired
    TipDao tipDao;

    /**
     * 获取联系人列表
     *
     * @param serviceContext
     * @return
     */
    public List<Map<String, Object>> getChatList(ServiceContext serviceContext) {
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        String token = serviceContext.getParamsString("token");
        User user = userDao.findUserByToken(token);
        List<Chat> chatListList = chatDao.getChatListByUserId(user.getId(), serviceContext.getPage(), serviceContext.getLimit());
        for (Chat chatList : chatListList) {
            Tip tip = tipDao.getTipById(chatList.getTipId());
            Map<String, Object> resultMap = new HashMap<>(10);
            resultMap.put("unreadCount", chatList.getUnreadCount());
            resultMap.put("listContent", chatList.getContent());
            resultMap.put("title", tip.getTitle());
            resultMap.put("tipId", tip.getId());
            resultMap.put("updateTime", ChatUtil.getChatUpdateTime(chatList.getUpdateTime()));
            User toUser = userDao.findUserById(chatList.getToUserId());
            resultMap.put("toNickName", toUser.getNickName());
            resultMap.put("toHeadImg", toUser.getHeadImg());
            resultMap.put("toUserId", toUser.getId());
            resultList.add(resultMap);
        }
        return resultList;
    }

    /**
     * 获取聊天记录
     *
     * @param serviceContext
     * @return
     */
    public List<Map<String, Object>> getChatRecord(ServiceContext serviceContext) {
        String token = serviceContext.getParamsString("token");
        Integer tipId = serviceContext.getParamsInteger("tipId");
        Integer toUserId = serviceContext.getParamsInteger("toUserId");
        User user = userDao.findUserByToken(token);
        User toUser = userDao.findUserById(toUserId);
        List<ChatRecord> chatRecordList = chatDao.getChaRecordByUserId(user.getId(), toUserId, tipId, serviceContext.getPage(), serviceContext.getLimit());
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        for (ChatRecord chatRecord : chatRecordList) {
            String content = chatRecord.getContent();
            Map<String, Object> recordMap = new HashMap<>(10);
            //如果非文字和非图片
            if (chatRecord.getContentType() == ChatService.text || chatRecord.getContentType() == ChatService.img) {
                recordMap.put("content", content);
            } else if (chatRecord.getContentType() == ChatService.date) {
                recordMap.put("content", ChatUtil.getDateContent(content, chatRecord.getCreateTime()));
            } else {
                JSONObject mapJson = JSON.parseObject(content);
                recordMap.put("content", mapJson);
            }
            recordMap.put("contentType", chatRecord.getContentType());
            recordMap.put("userId", chatRecord.getUserId());
            recordMap.put("toUserId", toUser.getId());
            recordMap.put("toNickName", toUser.getNickName());
            recordMap.put("toHeadImg", toUser.getHeadImg());
            recordMap.put("createTime", chatRecord.getCreateTime());
            resultList.add(recordMap);
        }
        if (chatRecordList.size() > 0) {
            //chatDao.haveRead(user.getId(), toUserId, tipId);
        }
        return resultList;
    }

    /**
     * 发送消息
     *
     * @param serviceContext
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendMessage(ServiceContext serviceContext) {
        String token = serviceContext.getParamsString("token");
        Integer tipId = serviceContext.getParamsInteger("tipId");
        Integer toUserId = serviceContext.getParamsInteger("toUserId");
        Integer contentType = serviceContext.getParamsInteger("contentType");
        String content = serviceContext.getParamsString("content");
        User user = userDao.findUserByToken(token);
        Integer userId = user.getId();
        if (userId.intValue() == toUserId) {
            throw BusinessException.getInstance("自己不能和自己聊天");
        }
        chatDao.saveChatRecord(userId, toUserId, tipId, contentType, content);
        Tip tip = tipDao.getTipById(tipId);
        JSONObject sendMsgContent = new JSONObject();
        sendMsgContent.put("title", tip.getTitle());
        sendMsgContent.put("tipId", tip.getId());
        sendMsgContent.put("updateTime", ChatUtil.getChatUpdateTime(new Date()));
        sendMsgContent.put("userId", userId);
        sendMsgContent.put("toUserId", user.getId());
        sendMsgContent.put("toNickName", user.getNickName());
        sendMsgContent.put("toHeadImg", user.getHeadImg());
        sendMsgContent.put("contentType", contentType);
        sendMsgContent.put("unreadCount", 1);
        //如果非文字和非图片
        if (contentType == ChatService.text || contentType == ChatService.img || contentType == ChatService.date) {
            sendMsgContent.put("content", content);
        } else {
            JSONObject mapJson = JSON.parseObject(content);
            sendMsgContent.put("content", mapJson);
        }
        String textContent = ChatUtil.getContent(contentType, content);
        sendMsgContent.put("listContent", textContent);
        //发送及时消息
        Boolean sendBool = SendSocketMessage.sendText(toUserId, sendMsgContent.toJSONString());
        if (!sendBool && contentType != ChatService.date) {
            sendMiniProgramMessage(toUserId, tip.getTitle(), user.getNickName(), textContent);
        }
    }


    /**
     * 删除联系人
     *
     * @param serviceContext
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteChat(ServiceContext serviceContext) {
        String token = serviceContext.getParamsString("token");
        Integer tipId = serviceContext.getParamsInteger("tipId");
        Integer toUserId = serviceContext.getParamsInteger("toUserId");
        User user = userDao.findUserByToken(token);
        //保存消息和联系人
        chatDao.deleteChat(user.getId(), toUserId, tipId);
    }

    /**
     * 已读
     *
     * @param serviceContext
     */
    @Transactional(rollbackFor = Exception.class)
    public void haveRead(ServiceContext serviceContext) {
        String token = serviceContext.getParamsString("token");
        Integer tipId = serviceContext.getParamsInteger("tipId");
        Integer toUserId = serviceContext.getParamsInteger("toUserId");
        User user = userDao.findUserByToken(token);
        chatDao.haveRead(user.getId(), toUserId, tipId);
    }

    public void sendMiniProgramMessage(Integer toUserId, String title, String nickName, String content) {
        String pageUrl = "/pages/chatList";
        String templateId = "OfoIzhkfZuZaM1KS3eBs10saJpWGvfPqhG2kSZDtxO4";
        Map<String, Object> dataMap = new HashMap<>(3);
        Map<String, Object> value1Map = new HashMap<>(1);
        value1Map.put("value", title);
        dataMap.put("keyword1", value1Map);
        Map<String, Object> value2Map = new HashMap<>(1);
        value2Map.put("value", nickName);
        dataMap.put("keyword2", value2Map);
        Map<String, Object> value3Map = new HashMap<>(1);
        value3Map.put("value", DateUtil.parseToString(new Date(), DateUtil.DATEFORMAT_YYYYMMDDHHMMSS));
        dataMap.put("keyword3", value3Map);
        Map<String, Object> value4Map = new HashMap<>(1);
        value4Map.put("value", content);
        dataMap.put("keyword4", value4Map);
        User toUser = userDao.findUserById(toUserId);
        UserForm userForm = userDao.findFrom(toUser.getId());
        if (userForm != null) {
            MiniProgramUtil.sendMiniProgramMessage(toUser.getOpenId(), templateId, pageUrl, userForm.getFormId(), dataMap);
            userForm.setValid(false);
            userDao.saveUserForm(userForm);
        } else {
            //需要发短信吗？
        }
    }
}
